package com.sunshine.lnuplus.ui.activity

import android.annotation.SuppressLint
import android.content.DialogInterface
import android.nfc.cardemulation.HostNfcFService
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.widget.EditText
import com.sunshine.lnuplus.R
import com.sunshine.lnuplus.base.BaseActivity
import com.sunshine.lnuplus.internet.ToXiaoAi
import com.sunshine.lnuplus.utils.StatusBarUtils
import com.sunshine.lnuplus.utils.XiaoAiUtils
import com.sunshine.lnuplus.view.DialogWithoutView
import kotlinx.android.synthetic.main.activity_xiao_ai.*

class XiaoAiActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_xiao_ai)

        initView()
    }

    private fun initView() {
        title = "导出课表到小爱课表"
        StatusBarUtils.setStatusBarWithColor(this, color)
        arcView2.setColor(color, color)

        button_xiaoai_copy.setOnClickListener {
            when{
                edit_mi_id.text.toString().isEmpty() -> {
                    tip_mi_id.error = "请输入小米账号"
                    tip_mi_id.isErrorEnabled = true
                }
                edit_device_id.text.toString().isEmpty() -> {
                    tip_device_id.error = "请输入设备id"
                    tip_device_id.isErrorEnabled = true
                }
                else -> {
                    DialogWithoutView.newInstance(
                        "请注意",
                        "请确保输入的小米账号和设备id准备，建议在黄鸟中复制，否则会添加失败甚至添加到他人账号中",
                        false,
                        DialogInterface.OnClickListener { _, _ ->
                            handler.sendEmptyMessage(1)
                        },
                        null
                    ).show(supportFragmentManager, "")
                }
            }
        }
    }

    val handler = @SuppressLint("HandlerLeak")
    object : Handler(){
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if(msg.what == 1){
                val xiaoaiBeanList = XiaoAiUtils.lessonToXiaoAiJson(edit_device_id.text.toString(), edit_mi_id.text.toString())
                val id = R.id.edit_course1
                for (i in 0 until xiaoaiBeanList.size){
                    findViewById<EditText>(id + i).setText(xiaoaiBeanList[i])
                }
            }
        }
    }
}
